package com.example.textroom;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.text.DecimalFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/8/27 10:13
 */
public class DownloadUtils  {

    public interface DownloadCallback {
        void onSuccess(String filePath);
        void onError(String error);
        void onCancel();
    }


    File outputFile = null;
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    public void downloadFile(Context context, String downloadUrl, String fileName, DownloadCallback callback) {
        // 检查URL协议，如果是HTTP且需要安全处理
        if (downloadUrl.startsWith("http://")) {
            // 可以在这里添加提示或自动转换为HTTPS（如果支持）
            Log.w("DownloadUtils", "使用HTTP协议，建议使用HTTPS以确保安全");
        }

        // 创建并显示下载对话框
        Dialog downloadDialog = createDownloadDialog(context, fileName);
        downloadDialog.show();

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(Looper.getMainLooper());



        executor.execute(() -> {

            try {
                // 创建下载目录
                File downloadDir = context.getExternalFilesDir("Downloads");
                if (downloadDir == null) {
                    downloadDir = new File(context.getFilesDir(), "Downloads");
                }
                if (!downloadDir.exists()) {
                    downloadDir.mkdirs();
                }

                outputFile = new File(downloadDir, fileName);

                URL url = new URL(downloadUrl);
                connection = (HttpURLConnection) url.openConnection();

                // 设置超时时间
                connection.setConnectTimeout(15000);
                connection.setReadTimeout(15000);

                // 如果是HTTPS，设置SSL信任所有证书（谨慎使用）
                if (downloadUrl.startsWith("https://")) {
                    trustAllCertificates(connection);
                }

                connection.setRequestMethod("GET");
                connection.connect();

                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    throw new Exception("HTTP错误: " + responseCode);
                }

                long fileSize = connection.getContentLength();
                inputStream = connection.getInputStream();
                outputStream = new FileOutputStream(outputFile);

                byte[] buffer = new byte[8192];
                int bytesRead;
                long totalDownloaded = 0;
                long startTime = System.currentTimeMillis();
                long lastUpdateTime = startTime;
                long lastDownloaded = 0;

                // 初始化进度
                handler.post(() -> updateProgress(downloadDialog, 0, fileSize, 0));

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalDownloaded += bytesRead;

                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastUpdateTime >= 500) {
                        long elapsedTime = currentTime - lastUpdateTime;
                        long downloadSpeed = (totalDownloaded - lastDownloaded) * 1000 / elapsedTime;

                        final long finalTotalDownloaded = totalDownloaded;
                        final long finalFileSize = fileSize;
                        final long finalDownloadSpeed = downloadSpeed;

                        handler.post(() -> updateProgress(downloadDialog, finalTotalDownloaded, finalFileSize, finalDownloadSpeed));

                        lastUpdateTime = currentTime;
                        lastDownloaded = totalDownloaded;
                    }
                }

                outputStream.flush();

                // 下载完成
                handler.post(() -> {
                    downloadDialog.dismiss();
                    Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
                    callback.onSuccess(outputFile.getAbsolutePath());
                });

            } catch (Exception e) {
                // 删除可能已创建的部分文件
                if (outputFile != null && outputFile.exists()) {
                    outputFile.delete();
                }

                handler.post(() -> {
                    downloadDialog.dismiss();
                    String errorMsg = e.getMessage();
                    if (errorMsg != null && errorMsg.contains("Cleartext")) {
                        errorMsg = "HTTP通信被阻止，请使用HTTPS或配置网络安全";
                    }
                    callback.onError(errorMsg);
                });

            } finally {
                try {
                    if (outputStream != null) outputStream.close();
                    if (inputStream != null) inputStream.close();
                    if (connection != null) connection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                executor.shutdown();
            }
        });

        // 设置取消按钮监听
        Button btnCancel = downloadDialog.findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(v -> {
            executor.shutdownNow();
            downloadDialog.dismiss();
            callback.onCancel();
        });
    }

    /**
     * 信任所有SSL证书（仅用于测试环境，生产环境不推荐使用）
     */
    private static void trustAllCertificates(HttpURLConnection connection) {
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            try {
                // 创建信任所有证书的SSL上下文
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{
                        new X509TrustManager() {
                            public X509Certificate[] getAcceptedIssuers() {
                                return new X509Certificate[0];
                            }
                            public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                        }
                }, new java.security.SecureRandom());

                httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                httpsConnection.setHostnameVerifier((hostname, session) -> true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static Dialog createDownloadDialog(Context context, String fileName) {
        Dialog dialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Light_Dialog);
        dialog.setContentView(R.layout.dialog_download);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        TextView tvFileName = dialog.findViewById(R.id.tvFileName);
        tvFileName.setText(fileName);

        return dialog;
    }

    private static void updateProgress(Dialog dialog, long downloaded, long total, long speed) {
        ProgressBar progressBar = dialog.findViewById(R.id.progressBar);
        TextView tvProgress = dialog.findViewById(R.id.tvProgress);
        TextView tvRemaining = dialog.findViewById(R.id.tvRemaining);

        if (total > 0) {
            int progress = (int) (downloaded * 100 / total);
            progressBar.setProgress(progress);

            String progressText = formatFileSize(downloaded) + "/" + formatFileSize(total);
            tvProgress.setText(progressText);

            if (speed > 0) {
                long remainingBytes = total - downloaded;
                long remainingSeconds = remainingBytes / speed;
                tvRemaining.setText("还剩 " + remainingSeconds + "秒");
            } else {
                tvRemaining.setText("还剩 --");
            }
        }
    }

    private static String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}
